﻿using Basic.FormDAL.Model;
using Basic.FormModel.DB;
using SqlSugar;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FormDAL.Repository
{
    internal class PhysicalQueryGroupDAL : BasicDAL<DBPhysicalQueryGroup, long>, IPhysicalQueryGroupDAL
    {
        public PhysicalQueryGroupDAL ( IRepository<DBPhysicalQueryGroup> basicDAL ) : base(basicDAL, "physical.query.group")
        {
        }

        public long Add ( DBPhysicalQueryGroup add )
        {
            add.Id = IdentityHelper.CreateId();
            this._BasicDAL.Insert(add);
            return add.Id;
        }

        public int GetMaxSort ( long tableId, long parentId )
        {
            ISugarQueryable<MaxSortDto>[] tables = new ISugarQueryable<MaxSortDto>[]
            {
                this._BasicDAL.Queryable.Where(a=>a.TableId==tableId && a.ParentId==parentId).Select(a=>new MaxSortDto
                {
                    Sort=a.Sort
                }),
                this._BasicDAL.Provider.Queryable<DBPhysicalQueryColumn>().Where(a=>a.TableId==tableId && a.GroupId==parentId).Select(a=>new MaxSortDto
                {
                    Sort=a.Sort
                })
            };
            return this._BasicDAL.Provider.UnionAll<MaxSortDto>(tables).Max(a => a.Sort);
        }
    }
}
